package com.cscec5b.inspection.repository;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class TaskUpsertRepository {

    @PersistenceContext
    private EntityManager em;

    // 最小修复版：对齐表结构，仅写你现在传入的字段
    private static final String UPSERT_SQL = """
        INSERT INTO tasks
          (task_id, project_inner_number, subproject_name, inspect_rule,
           task_type, task_location, task_volume, design_values)
        VALUES
          (:taskId, :projectInnerNumber, :subprojectName, :inspectRule,
           :taskType, :taskLocation, :taskVolume, :designValues)
        ON DUPLICATE KEY UPDATE
          project_inner_number = VALUES(project_inner_number),
          subproject_name      = VALUES(subproject_name),
          inspect_rule         = VALUES(inspect_rule),
          task_type            = VALUES(task_type),
          task_location        = VALUES(task_location),
          task_volume          = VALUES(task_volume),
          design_values        = VALUES(design_values)
        """;

    @Transactional
    public int upsertTask(Integer taskId,
                          String projectInnerNumber,
                          String subprojectName,
                          String inspectRule,
                          String taskType,
                          String taskLocation,   // ← 参数名对齐
                          String taskVolumeJson,
                          String designValuesJson) {
        var q = em.createNativeQuery(UPSERT_SQL);
        q.setParameter("taskId", taskId);
        q.setParameter("projectInnerNumber", projectInnerNumber);
        q.setParameter("subprojectName", subprojectName);
        q.setParameter("inspectRule", inspectRule);
        q.setParameter("taskType", taskType);
        q.setParameter("taskLocation", taskLocation); // ← 对应 :taskLocation
        q.setParameter("taskVolume", taskVolumeJson);
        q.setParameter("designValues", designValuesJson);
        return q.executeUpdate();
    }
}
